<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/8/3 13:46
 * Modified Time: 2019/8/3 13:46
 * Version: 2.0
 */

namespace App\Modules\MemberCard\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use function foo\func;
use Illuminate\Support\Facades\DB;

class GetTransferMemberCardListCriteria extends BaseCriterias
{
    protected $store_id;
    protected $keywords;

    public function __construct($store_id, $keywords)
    {
        $this->store_id = $store_id;
        $this->keywords = $keywords;
    }

    public function apply($model, RepositoryInterface $repository)
    {

        $keywords = $this->keywords;
        $store_id = $this->store_id;

        $select = [
            'hx_member_card.id',
            'hx_member_card.name',
            'hx_member_card.attribute',
            'IF(member_id=0,0,1) as has_receive',
            'hx_member_card.type_id',
            'hx_member_card.count',
            'hx_member_card.balance',
            'hx_member_card.mobile',
            'hx_card_type.name as card_name',
            'hx_member_card.created_at as created_time'
        ];

        $select = implode($select, ',');


        $model = $model->selectRaw($select)
            ->leftJoin('card_type', 'member_card.type_id', 'card_type.id')
            ->with(['cardType' => function ($query) {
                $query->select(['id'])->with(['cardTypeService' => function ($query) {
                    $query->select(['store_service.id', 'type_id', 'store_service.name'])
                        ->leftJoin('store_service', 'store_service.id', 'card_type_service.service_id');
                }]);
            }])
            ->where(function ($query){
                $query->where('source', 2)->orWhere('source', 3);
            })
            ->where('member_card.store_id', $store_id)
            ->when($keywords!==null, function ($query) use ($keywords) {
                $query->where('member_card.name', 'like', '%' . $keywords . '%')
                    ->orWhere('member_card.mobile', 'like', '%' . $keywords . '%');
            })
            ->where('member_card.store_id', $store_id)->orderBy('id','DESC');


        return $model;
    }
}